package com.yylending.las.lending.quota.myquota;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yylending.las.Constants;
import com.yylending.las.Global;
import com.yylending.las.lending.QuotaEvent;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 我的额度Presenter
 * Created by laixj on 2016/11/18.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class MyQuotaPresenter extends Presenter<MyQuotaModel, MyQuotaPresenter.View> {
	private final static String TAG = "MyQuotaPresenter";
	private static final String RET_CODE_SUBMIT_STATUS_CREDIT_EXPIRED = "100040"; // 征信过期

	public static class Generator implements PresenterFactory<MyQuotaPresenter> {
		@Override
		public MyQuotaPresenter create() {
			return new MyQuotaPresenter();
		}
	}

	public interface View extends IView {
		/**
		 * "10": 有在途借款申请（非云贷）; "20": 已有在途借款; "100": 未获取额度; "110": 额度获取中; "120": 不符合要求;
		 * "130": 低额度（额度小于阈值且可提额300:直接填保单；额度小于阈值且提额申请中320：显示保单提交完成；额度高于阈值且可提额300：显示提额入口；额度高于阈值且提额申请中320：不显示提额入口；额度高于阈值且无提额310：不显示提额入口）;
		 * "140": 高额度
		 * "300":"可提额; "310": 无提额; "320": 提额申请中
		 * "200": 借款申请中; "210": 需要现调; "220": 需要远程面签; "230": 审核中; "240": 借款否决; "250": 审批通过
		 * threshold：额度阈值
		 */
		/**
		 * 有在途借款申请（非云贷）
		 */
		void showLoanPage(int page, MyQuotaModel.ApplyStatus result);

		/**
		 * 获取我的额度请求失败
		 */
		void getStatusFail(String msg);

		/**
		 * 征信过期
		 */
		void creditReportingOutdated();
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new MyQuotaModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	/**
	 * 我的额度申请状态
	 */
	public void myQuota() {
		execute(null, MyQuotaModel.METHOD_MY_QUOTA, false, null, mRequestPage);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void myQuotaResult(MyQuotaModel.MyQuotaResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			if (BaseResultEntity.isResponseSuccess(result) && null != result.getData()) {
				MyQuotaModel.ApplyStatus rs = result.getData();
				if (null != rs.loanLine) {
					try {
						Global.mMinOnlineQuota = Integer.valueOf(rs.loanLine.loanLineAmount);
						Global.mMaxOnlineQuota = Integer.valueOf(rs.loanLine.highLoanLine);
						CLog.i(TAG, "获取阈值Global.mMinOnlineQuota=" + Global.mMinOnlineQuota);
						CLog.i(TAG, "获取阈值Global.mMaxOnlineQuota=" + Global.mMaxOnlineQuota);
					} catch (Exception e) {
						CLog.i(TAG, "获取额度阈值失败");
					}
				}
				judgeQuotaStatus(rs);
			} else if (RET_CODE_SUBMIT_STATUS_CREDIT_EXPIRED.equals(result.getRetCode())) {
				mView.creditReportingOutdated();
			} else {
				mView.getStatusFail(null);
			}
		}
	}

	/**
	 * 判断额度状态
	 */
	private void judgeQuotaStatus(MyQuotaModel.ApplyStatus status) {
		if (!TextUtils.equals(Constants.QUOTA_STATUS_NOTYET, status.amountState)) {
			EventAgent.post(new QuotaEvent.DismissCodeVerifyDialogEvent());
		}
		switch (status.amountState) {
			case Constants.QUOTA_STATUS_HAVE_LOAN_OTHER:
				if (hasOfflineQuota(status)) {
					mView.showLoanPage(Constants.PAGE_COMPLEX_STATUS, status);
				} else {
					mView.showLoanPage(Constants.PAGE_NOT_APPLY, status);
				}
				break;
			case Constants.QUOTA_STATUS_HAVE_LOAN:
				mView.showLoanPage(Constants.PAGE_COMPLEX_STATUS, status);
				break;
			case Constants.QUOTA_STATUS_NOTYET:
				mView.showLoanPage(Constants.PAGE_NOT_APPLY, status);
				break;
			case Constants.QUOTA_STATUS_ING:
				mView.showLoanPage(Constants.PAGE_CALCULATING, status);
				break;
			case Constants.QUOTA_STATUS_REFUSED:
				mView.showLoanPage(Constants.PAGE_ZERO_QUOTA, status);
				break;
			case Constants.QUOTA_STATUS_LOW:
				judgePromoteStatus(status);
				break;
			case Constants.QUOTA_STATUS_HIGH:
				if (TextUtils.isEmpty(status.loanState)) {
					if (Constants.PROMOTE_STATUS_ING.equals(status.promoteAmount)) {
						//提额申请中 需要显示提额loading界面
						EventAgent.post(new QuotaEvent.ShowIncreaseLoadingEvent());
					} else {
						mView.showLoanPage(Constants.PAGE_COMPLEX_STATUS, status);
					}
				} else {
					judgeLoanStatus(status);
				}
				break;
			default:
				if (TextUtils.isEmpty(status.amountState) && null != status.loanState && Constants.LOAN_STATUS_REFUSED.equals(status.loanState)) {
					mView.showLoanPage(Constants.PAGE_ZERO_QUOTA, status);
				} else {
					mView.getStatusFail(null);
				}
				break;
		}
	}

	/**
	 * 判断提额状态<p>
	 * 一、"130"：低额度<p>
	 * 1.额度小于阈值且promoteAmount=300(可提额) -> 直接填保单<p>
	 * 2.额度小于阈值且promoteAmount=320(提额申请中) -> 显示保单提交完成<p>
	 * 二、"140"：高额度<p>  高额度在界面里面去判断（只需要判断额度小于20万的直批）
	 * 1.额度高于阈值且promoteAmount=300(可提额) -> 显示提额入口<p>
	 * 2.额度高于阈值且promoteAmount=320(提额申请中) -> 不显示提额入口<p>
	 * 3.额度高于阈值且promoteAmount=310(无提额) -> 不显示提额入口<p>
	 */
	private void judgePromoteStatus(MyQuotaModel.ApplyStatus status) {
		switch (status.promoteAmount) {
			case Constants.PROMOTE_STATUS_HAVE:
				if (Constants.QUOTA_STATUS_LOW.equals(status.amountState)) {
					if (hasOfflineQuota(status)) {
						mView.showLoanPage(Constants.PAGE_LOW_QUOTA_OUTLET_APPOINTED, status);
					} else {
						mView.showLoanPage(Constants.PAGE_INCREASE, status);
					}
				}
				break;
			case Constants.PROMOTE_STATUS_ING:
				if (Constants.QUOTA_STATUS_LOW.equals(status.amountState)) {
					//提额申请中 需要显示提额loading界面
					EventAgent.post(new QuotaEvent.ShowIncreaseLoadingEvent());
					//mView.showLoanPage(Constants.PAGE_INCREASE_SUCCESS, status);
				}
				break;
			case Constants.PROMOTE_STATUS_WITHOUT:
				if (Constants.QUOTA_STATUS_LOW.equals(status.amountState)) {
					if (hasOfflineQuota(status)) {
						mView.showLoanPage(Constants.PAGE_LOW_QUOTA_OUTLET_APPOINTED, status);
					} else {
						mView.showLoanPage(Constants.PAGE_INCREASE_SUCCESS, status);
					}
				}
				break;
			default:
				if (Constants.QUOTA_STATUS_LOW.equals(status.amountState) && hasOfflineQuota(status)) {
					mView.showLoanPage(Constants.PAGE_LOW_QUOTA_OUTLET_APPOINTED, status);
				}
				break;
		}
	}

	/**
	 * 判断借款状态
	 */
	private void judgeLoanStatus(MyQuotaModel.ApplyStatus status) {
		switch (status.loanState) {
			case Constants.LOAN_STATUS_NOT_DIRECT:
				// 显示非直批，暂时无这种情况
				mView.showLoanPage(Constants.PAGE_COMPLEX_STATUS, status);
				break;
			case Constants.LOAN_STATUS_ING:
			case Constants.LOAN_STATUS_VIDEO_AUTH:
			case Constants.LOAN_STATUS_REVIEW:
			case Constants.LOAN_WAIT_FOR_LOANING:
				mView.showLoanPage(Constants.PAGE_NO_LOAN_STATUS_RESEARCH, status);
				break;
			case Constants.LOAN_STATUS_REFUSED:
				mView.showLoanPage(Constants.PAGE_ZERO_QUOTA, status);
				break;
			default:
				break;
		}
	}

	/**
	 * 已出额度、借款申请提交后各种状态综合判断
	 *
	 * @param status
	 * @return
	 */
	public static int judgeComplexStatus(MyQuotaModel.ApplyStatus status) {
		int statusCode = 0;
		switch (status.amountState) {
			case Constants.QUOTA_STATUS_HAVE_LOAN_OTHER:
				//线下已预约
				if (hasOfflineQuota(status)) {
					//直批、线上未获取，线下已预约
					if (isDirectApproval(status)) {
						statusCode = Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_ONLY;
					} else if (isNotDirectApproval(status)) {
						//非直批，线下已预约
						statusCode = Constants.COMPLEX_STATUS_NOT_DIRECT_APPOINTED;
					}
				}
				break;
			case Constants.QUOTA_STATUS_HAVE_LOAN: {
				//直批
				if (isDirectApproval(status)) {
					if (largeThanMaxOnlineQuota(status)) {
						if (hasOfflineQuota(status)) {
							//直批且额度大于20W，线上已通过，线下已预约
							statusCode = Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_APPOINTED;
						} else {
							//直批且额度大于20W，线上已通过，线下无额度
							statusCode = Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_NONE;
						}
					} else {
						//直批且额度小于20W，借款申请已通过
						statusCode = Constants.COMPLEX_STATUS_DIRECT_LOW_PASSED;
					}
				} else if (isNotDirectApproval(status)) {
					//非直批，借款申请已通过
					statusCode = Constants.COMPLEX_STATUS_NOT_DIRECT_PASSED;
				} else {
					//已有存量借款
					statusCode = Constants.COMPLEX_STATUS_HAS_LOAN;
				}
				break;
			}
			case Constants.QUOTA_STATUS_HIGH:
				if (TextUtils.isEmpty(status.loanState)) {
					//Y :直批  N：非直批
					if (isDirectApproval(status)) {
						// 直批界面
						if (largeThanMaxOnlineQuota(status) && !hasOfflineQuota(status)) {
							//直批且额度大于20W，均未申请
							statusCode = Constants.COMPLEX_STATUS_DIRECT_HIGH_BOTH;
						} else {
							//小于20W、直批
							statusCode = Constants.COMPLEX_STATUS_DIRECT_LOW;
						}
					} else if (isNotDirectApproval(status)) {
						// 非直批界面
						if (hasOfflineQuota(status)) {
							//非直批，已预约
							statusCode = Constants.COMPLEX_STATUS_NOT_DIRECT_APPOINTED;
						} else {
							//非直批，未预约
							statusCode = Constants.COMPLEX_STATUS_NOT_DIRECT;
						}
					}
				}
				break;
			default:
				break;
		}
		return statusCode;
	}

	/**
	 * 是否直批
	 *
	 * @param status
	 * @return
	 */
	public static boolean isDirectApproval(MyQuotaModel.ApplyStatus status) {
		if (null == status) {
			return false;
		}
		return !TextUtils.isEmpty(status.isDirectApproval) && "Y".equals(status.isDirectApproval);
	}

	/**
	 * 是否非直批
	 *
	 * @param status
	 * @return
	 */
	public static boolean isNotDirectApproval(MyQuotaModel.ApplyStatus status) {
		if (null == status) {
			return false;
		}
		return !TextUtils.isEmpty(status.isDirectApproval) && "N".equals(status.isDirectApproval);
	}

	/**
	 * 是否有线下额度
	 *
	 * @param status
	 * @return
	 */
	public static boolean hasOfflineQuota(MyQuotaModel.ApplyStatus status) {
		if (null == status) {
			return false;
		}
		return !TextUtils.isEmpty(status.offLineAmount) && "1".equals(status.offLineAmount);
	}

	/**
	 * 额度是否大于线上可借最大额度
	 *
	 * @param status
	 * @return
	 */
	public static boolean largeThanMaxOnlineQuota(MyQuotaModel.ApplyStatus status) {
		if (null == status) {
			return false;
		}
		int maxQuota = 0;
		try {
			maxQuota = Integer.parseInt(status.quota.ts);
		} catch (NumberFormatException e) {
			CLog.e(TAG, "额度值转换异常");
		}
		return maxQuota > Global.mMaxOnlineQuota;
	}

	/**
	 * 额度是否小于线上可借最大额度
	 *
	 * @param status
	 * @return
	 */
	public static boolean lessThanMaxOnlineQuota(MyQuotaModel.ApplyStatus status) {
		if (null == status) {
			return false;
		}
		int maxQuota = 0;
		try {
			maxQuota = Integer.parseInt(status.quota.ts);
		} catch (NumberFormatException e) {
			CLog.e(TAG, "额度值转换异常");
		}
		return maxQuota < Global.mMaxOnlineQuota;
	}
}